

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="背景说明  当需要使用gopacket发送大量数据包时，频繁调用gopacket的handle.WritePacketData()会导致频繁的内核切换，这是不利的。 我们希望的是，尽量少的内核上下文切换情况下，发送尽可能多的数据   分析 通过阅读gopacket的源码，我们不难发现以下内容： gopacket只提供了一个发送数据的接口 : pcap.go   pcap_windows.go 1">
<meta property="og:type" content="article">
<meta property="og:title" content="Gopacket扩展-增加pcap_send_queue支持">
<meta property="og:url" content="http://example.com/2022/07/11/20220711-Gopacket%E6%89%A9%E5%B1%95-%E5%A2%9E%E5%8A%A0pcap-send-queue%E6%94%AF%E6%8C%81/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="背景说明  当需要使用gopacket发送大量数据包时，频繁调用gopacket的handle.WritePacketData()会导致频繁的内核切换，这是不利的。 我们希望的是，尽量少的内核上下文切换情况下，发送尽可能多的数据   分析 通过阅读gopacket的源码，我们不难发现以下内容： gopacket只提供了一个发送数据的接口 : pcap.go   pcap_windows.go 1">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-11T09:25:59.000Z">
<meta property="article:modified_time" content="2022-07-11T09:57:14.805Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="Golang">
<meta property="article:tag" content="gopacket">
<meta property="article:tag" content="通信">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Gopacket扩展-增加pcap_send_queue支持 - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Gopacket扩展-增加pcap_send_queue支持"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-11 17:25" pubdate>
          星期一, 七月 11日 2022, 5:25 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          5.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          43 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Gopacket扩展-增加pcap_send_queue支持</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="背景说明"><a class="markdownIt-Anchor" href="#背景说明"></a> 背景说明</h2>
<blockquote>
<p>当需要使用<code>gopacket</code>发送大量数据包时，频繁调用<code>gopacket</code>的<code>handle.WritePacketData()</code>会导致频繁的内核切换，这是不利的。</p>
<p>我们希望的是，尽量少的内核上下文切换情况下，发送尽可能多的数据</p>
</blockquote>
<h2 id="分析"><a class="markdownIt-Anchor" href="#分析"></a> 分析</h2>
<p>通过阅读<code>gopacket</code>的源码，我们不难发现以下内容：</p>
<p><code>gopacket</code>只提供了一个发送数据的接口 : <code>pcap.go</code>   <code>pcap_windows.go</code></p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// WritePacketData calls pcap_sendpacket, injecting the given data into the pcap handle.</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> WritePacketData(data []<span class="hljs-type">byte</span>) (err <span class="hljs-type">error</span>) &#123;<br>	<span class="hljs-keyword">return</span> p.pcapSendpacket(data)<br>&#125;<br><span class="hljs-comment">// pcap_windows.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> pcapSendpacket(data []<span class="hljs-type">byte</span>) <span class="hljs-type">error</span> &#123;<br>	ret, _, _ := syscall.Syscall(pcapSendpacketPtr, <span class="hljs-number">3</span>, <span class="hljs-type">uintptr</span>(p.cptr), <span class="hljs-type">uintptr</span>(unsafe.Pointer(&amp;data[<span class="hljs-number">0</span>])), <span class="hljs-type">uintptr</span>(<span class="hljs-built_in">len</span>(data)))<br>	<span class="hljs-keyword">if</span> pcapCint(ret) &lt; <span class="hljs-number">0</span> &#123;<br>		<span class="hljs-keyword">return</span> p.pcapGeterr()<br>	&#125;<br>	<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>&#125;<br><span class="hljs-comment">// pcap_windows.go</span><br>pcapSendpacketPtr = mustLoad(<span class="hljs-string">&quot;pcap_sendpacket&quot;</span>)<br><br></code></pre></td></tr></table></figure>
<p>小结：<code>gopacket</code>在windows平台下，通过底层调用<code>npcap</code>的动态库实现发包功能。具体调用<code>npcap</code>的<code>pcap_sendpacket</code>接口</p>
<h2 id="npcap-pcap_send_queue"><a class="markdownIt-Anchor" href="#npcap-pcap_send_queue"></a> npcap: pcap_send_queue</h2>
<blockquote>
<p>参考：<a target="_blank" rel="noopener" href="https://npcap.com/guide/npcap-api.html">The Npcap API | Npcap Reference Guide</a></p>
</blockquote>
<ul>
<li>描述：</li>
</ul>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs markdown">Queuing sent packets with <span class="hljs-code">`pcap_send_queue`</span><br><br>Npcap has the ability to queue multiple raw packets for transmission on the network in a single call. This is more efficient than issuing a series of <span class="hljs-code">`pcap_sendpacket()`</span>, because the packets are buffered in the kernel driver, so the number of context switches is reduced.<br></code></pre></td></tr></table></figure>
<ul>
<li>重点：<code>pcap_sned_queue</code>更高效，因为待发送的数据包被缓存到内核中，可以批量发送报文</li>
</ul>
<h2 id="扩展gopacket增加pcap_send_queue支持"><a class="markdownIt-Anchor" href="#扩展gopacket增加pcap_send_queue支持"></a> 扩展gopacket，增加pcap_send_queue支持</h2>
<h3 id="1-总览及思路"><a class="markdownIt-Anchor" href="#1-总览及思路"></a> 1. 总览及思路</h3>
<p>主要是增加对<code>pcap_send_queue</code>的系统调用，并且需要实现其对应的几个函数，包括</p>
<ul>
<li><code>pcap_sendqueue_alloc</code>：申请队列空间</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs c">pcap_send_queue* <span class="hljs-title function_">pcap_sendqueue_alloc</span><span class="hljs-params">(u_int memsize)</span>;<br></code></pre></td></tr></table></figure>
<ul>
<li><code>pcap_sendqueue_destroy</code>：释放队列空间</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-type">void</span> <span class="hljs-title function_">pcap_sendqueue_destroy</span><span class="hljs-params">(pcap_send_queue* <span class="hljs-built_in">queue</span>)</span>;<br></code></pre></td></tr></table></figure>
<ul>
<li><code>pcap_sendqueue_queue</code>：将报文数据压入队列</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-type">int</span> <span class="hljs-title function_">pcap_sendqueue_queue</span><span class="hljs-params">(pcap_send_queue* <span class="hljs-built_in">queue</span>, <span class="hljs-type">const</span> <span class="hljs-keyword">struct</span> pcap_pkthdr *pkt_header, <span class="hljs-type">const</span> u_char *pkt_data)</span>;<br></code></pre></td></tr></table></figure>
<ul>
<li><code>pcap_sendqueue_transmit</code>：发送队列</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs c">u_int <span class="hljs-title function_">pcap_sendqueue_transmit</span><span class="hljs-params">(<span class="hljs-type">pcap_t</span> *p, pcap_send_queue* <span class="hljs-built_in">queue</span>, <span class="hljs-type">int</span> sync)</span>;<br></code></pre></td></tr></table></figure>
<h3 id="2-注意事项"><a class="markdownIt-Anchor" href="#2-注意事项"></a> 2 注意事项</h3>
<p>在参数中，有一个重要的结构体<code>pkt_header</code>，它的结构如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">type</span> pcapPkthdr <span class="hljs-keyword">struct</span> &#123;<br>    <span class="hljs-comment">// 报文时间戳</span><br>	Ts     timeval<br>    <span class="hljs-comment">// length of portion present</span><br>	Caplen <span class="hljs-type">uint32</span><br>	Len    <span class="hljs-type">uint32</span><br>    <span class="hljs-comment">// length this packet (off wire)</span><br>&#125; <span class="hljs-comment">// pcap/defs_windows_amd64.go</span><br></code></pre></td></tr></table></figure>
<p><code>pkt_header</code>的头部中含有时间戳，因此在发送时，可以设置<code>sync=1</code>让网卡严格按照时间戳大小发送报文</p>
<p>其次，在<code>pcap_sendqueue_alloc</code>申请空间时，需要考虑<code>pkt_header</code>的大小。举例说明，如果报文长度是1500B，那么在队列中的报文长度实际上为<code>1500 + len(pkt_header) = 1516B</code></p>
<h3 id="3-实现"><a class="markdownIt-Anchor" href="#3-实现"></a> 3 实现</h3>
<h4 id="31-pcappcap_windowsgo"><a class="markdownIt-Anchor" href="#31-pcappcap_windowsgo"></a> 3.1 pcap/pcap_windows.go</h4>
<ul>
<li>
<p>增加相应函数指针</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">var</span> (<br>    pcapSendqueueallocPtr,<br>	pcapSendqueuedestroyPtr,<br>	pcapSendqueuequeuePtr,<br>	pcapSendqueuetransmitPtr <span class="hljs-type">uintptr</span><br>)<br></code></pre></td></tr></table></figure>
</li>
<li>
<p>为指针加载相应的系统调用</p>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 在 LoadWinPCAP()中增加</span><br>pcapSendqueueallocPtr = mustLoad(<span class="hljs-string">&quot;pcap_sendqueue_alloc&quot;</span>)<br>pcapSendqueuedestroyPtr = mustLoad(<span class="hljs-string">&quot;pcap_sendqueue_destroy&quot;</span>)<br>pcapSendqueuequeuePtr = mustLoad(<span class="hljs-string">&quot;pcap_sendqueue_queue&quot;</span>)<br>pcapSendqueuetransmitPtr = mustLoad(<span class="hljs-string">&quot;pcap_sendqueue_transmit&quot;</span>)<br></code></pre></td></tr></table></figure>
<ul>
<li>实现私有函数，提供给公有函数调用（pcap.go调用）</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// memsize 是以字节衡量的大小</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> pcapSendqueuealloc(memsize <span class="hljs-type">uint64</span>) (*<span class="hljs-type">uintptr</span>, <span class="hljs-type">error</span>) &#123;<br>	<span class="hljs-comment">//函数签名：   pcap_send_queue * 	pcap_sendqueue_alloc (u_int memsize)</span><br>	sendQueuePtr, _, _ := syscall.SyscallN(pcapSendqueueallocPtr, <span class="hljs-type">uintptr</span>(memsize))<br>	<span class="hljs-keyword">if</span> pcapCint(sendQueuePtr) == <span class="hljs-number">0</span> &#123;<br>		<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, errors.New(<span class="hljs-string">&quot;alloc a send queue error&quot;</span>)<br>	&#125;<br>	<span class="hljs-comment">// sendQueuePtr 是一块内存空间的首地址</span><br>	<span class="hljs-keyword">return</span> &amp;sendQueuePtr, <span class="hljs-literal">nil</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> pcapSendqueuedestroy(queue *<span class="hljs-type">uintptr</span>) &#123;<br>	<span class="hljs-comment">// 函数签名： void pcap_sendqueue_destroy	(	pcap_send_queue * 	queue	 )</span><br>	<span class="hljs-comment">// 释放空间</span><br>	syscall.SyscallN(pcapSendqueuedestroyPtr, *queue)<br><br>&#125;<br><br><span class="hljs-comment">// 返回pcapPkthdr的结构体长度，用于send_queue_alloc时申请空间</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">GetPcapPkthdrLength</span><span class="hljs-params">()</span></span> <span class="hljs-type">int</span> &#123;<br>	a := unsafe.Sizeof(pcapPkthdr&#123;&#125;)<br>	<span class="hljs-comment">// fmt.Printf(&quot;%#v\n&quot;, a)</span><br>	<span class="hljs-keyword">return</span> <span class="hljs-type">int</span>(a)<br>&#125;<br><br><span class="hljs-comment">// 添加一个packet到发送队列中</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> pcapSendqueuequeue(queue *<span class="hljs-type">uintptr</span>, pktData []<span class="hljs-type">byte</span>) <span class="hljs-type">error</span> &#123;<br>	<span class="hljs-comment">//var hdr pcapPkthdr</span><br>	<span class="hljs-comment">//	pcap_pkthdr 结构，包含当前包的时间戳和长度</span><br>	<span class="hljs-comment">//	pkt_data 只想包数据缓存区</span><br>	<span class="hljs-keyword">var</span> hdr pcapPkthdr<br>	hdr.Ts.Sec = <span class="hljs-type">int32</span>(time.Now().Unix())<br>	hdr.Ts.Usec = <span class="hljs-type">int32</span>(time.Now().Nanosecond() / <span class="hljs-number">1000</span>)<br>	hdr.Caplen = <span class="hljs-type">uint32</span>(<span class="hljs-built_in">len</span>(pktData)) <span class="hljs-comment">// Trust actual length over ci.Length.</span><br>	<span class="hljs-comment">// 当前包的长度</span><br>	hdr.Len = <span class="hljs-type">uint32</span>(<span class="hljs-built_in">len</span>(pktData))<br>    <br>	_, _, errno := syscall.SyscallN(pcapSendqueuequeuePtr, *queue, <span class="hljs-type">uintptr</span>(unsafe.Pointer(&amp;hdr)), <span class="hljs-type">uintptr</span>(unsafe.Pointer(&amp;pktData[<span class="hljs-number">0</span>])))<br>	<span class="hljs-keyword">if</span> errors.Is(errno, <span class="hljs-literal">nil</span>) &#123;<br>		<span class="hljs-keyword">return</span> fmt.Errorf(<span class="hljs-string">&quot;pcaperr=%v errno=%v&quot;</span>, p.pcapGeterr(), errno)<br>	&#125;<br>	<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>&#125;<br><br><span class="hljs-comment">// send queue</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> pcapSendqueuetransmit(queue *<span class="hljs-type">uintptr</span>, sync <span class="hljs-type">int</span>) <span class="hljs-type">error</span> &#123;<br>	ret, _, _ := syscall.SyscallN(pcapSendqueuetransmitPtr, <span class="hljs-type">uintptr</span>(p.cptr), *queue, <span class="hljs-type">uintptr</span>(sync))<br>	<span class="hljs-keyword">if</span> pcapCint(ret) &lt; <span class="hljs-number">0</span> &#123;<br>		<span class="hljs-keyword">return</span> p.pcapGeterr()<br>	&#125;<br>	<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h4 id="32-pcappcapgo"><a class="markdownIt-Anchor" href="#32-pcappcapgo"></a> 3.2 pcap/pcap.go</h4>
<blockquote>
<p>3.1 实现的特定平台下的私有函数接口。<code>pcap.go</code>实现一个公有函数调用它们，并提供给外部函数调用。</p>
</blockquote>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 假设packets的每一行是一个报文， 报文长度固定为 onePacketLength</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Handle)</span></span> WriteQueuePacket(packets [][]<span class="hljs-type">byte</span>, onePacketLength <span class="hljs-type">int</span>, sync <span class="hljs-type">int</span>) (err <span class="hljs-type">error</span>) &#123;<br>	<span class="hljs-comment">// 1. 申请空间</span><br>	cnt := <span class="hljs-built_in">len</span>(packets)<br>	pktHdrLen := GetPcapPkthdrLength()<br>	onePacketLength += pktHdrLen<br>	needMemSize := (cnt + cnt/<span class="hljs-number">5</span>) * onePacketLength<br>	sendQueue, err := p.pcapSendqueuealloc(<span class="hljs-type">uint64</span>(needMemSize))<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		fmt.Println(<span class="hljs-string">&quot;err when send-queue-alloc&quot;</span>)<br>		<span class="hljs-keyword">return</span> err<br>	&#125;<br>	<span class="hljs-keyword">defer</span> p.pcapSendqueuedestroy(sendQueue)<br>	<span class="hljs-comment">// 2. 填入数据</span><br>	<span class="hljs-keyword">for</span> _, pkt := <span class="hljs-keyword">range</span> packets &#123;<br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(pkt) == <span class="hljs-number">0</span> &#123;<br>			<span class="hljs-keyword">return</span> errors.New(<span class="hljs-string">&quot;packet is empty&quot;</span>)<br>		&#125;<br>		err = p.pcapSendqueuequeue(sendQueue, pkt)<br>		<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>			fmt.Printf(<span class="hljs-string">&quot;err when send-queue-queue\n&quot;</span>)<br>			<span class="hljs-keyword">return</span> err<br>		&#125;<br>	&#125;<br><br>	<span class="hljs-comment">// 3. 发送</span><br>	<span class="hljs-comment">// 非零则按时间戳发送</span><br>	err = p.pcapSendqueuetransmit(sendQueue, sync)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;err when send-queue-transmit\n&quot;</span>)<br>		<span class="hljs-keyword">return</span> err<br>	&#125;<br>	<span class="hljs-keyword">return</span> err<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="总结"><a class="markdownIt-Anchor" href="#总结"></a> 总结</h2>
<p>实验就不放上来了。实验结果就是在1Gbps的网卡中，如果仅使用<code>pcap_sendpacket</code>，可以达到<code>250Mbps</code>这样，而如果使用<code>pcap_send_queue</code>可以达到<code>800-900Mbps</code></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Golang/" class="category-chain-item">Golang</a>
  
  
    <span>></span>
    
  <a href="/categories/Golang/gopacket/" class="category-chain-item">gopacket</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Golang/">#Golang</a>
      
        <a href="/tags/gopacket/">#gopacket</a>
      
        <a href="/tags/%E9%80%9A%E4%BF%A1/">#通信</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Gopacket扩展-增加pcap_send_queue支持</div>
      <div>http://example.com/2022/07/11/20220711-Gopacket扩展-增加pcap-send-queue支持/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月11日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/07/13/20220713-MongoDB-%E5%88%9D%E8%AF%86/" title="MongoDB-初识">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">MongoDB-初识</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/06/29/20220629-gopacket/" title="gopacket基本使用">
                        <span class="hidden-mobile">gopacket基本使用</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
